package com.frog.framework.ms.api.dto;

import java.beans.Transient;
import java.io.Serializable;

/**
 * 所有API接口的返回封装类
 * @author wuqiong 2022/2/28
 */
public class ApiResult<T> implements Serializable {

    private static final long serialVersionUID = -3773644835471001861L;
    /**
     * 可以参考 {@link ApiResultCode}  也可以根据业务自定义
     */
    private int code;

    /**
     * 返回数据的描述信息
     */
    private String msg;

    /**
     * 返回的数据
     */
    private T data;

    public int getCode() {
        return code;
    }

    public ApiResult() {
        super();
    }

    public ApiResult(int code, T data) {
        this.code = code;
        this.data = data;
    }

    public ApiResult(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public ApiResult(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <T> ApiResult<T> successResult(T data) {
        return new ApiResult<>(ApiResultCode.SUCCESS, data);
    }

    /**
     * 系统错误返回信息
     * @author wuqiong 2022/2/28 17:01
     */
    public static <T> ApiResult<T> sysErrorResult(String msg) {
        return new ApiResult<>(ApiResultCode.SYS_ERROR, msg);
    }

    /**
     * 参数错误返回信息
     * @author wuqiong 2022/2/28 16:58
     */
    public static <T> ApiResult<T> paramErrorResult(String msg) {
        return new ApiResult<>(ApiResultCode.PARAM_ERROR, msg);
    }

    /**
     * 自定义返回信息及状态码
     * @author wuqiong 2022/2/28 17:02
     */
    public static <T> ApiResult<T> result(int code, String msg, T data) {
        return new ApiResult<>(code, msg, data);
    }

    public static final ApiResult<?> SUCCESS = ApiResult.successResult(null);

    public static final ApiResult<?> SYS_ERROR = new ApiResult<>(ApiResultCode.SYS_ERROR, "系统错误");

    public static final ApiResult<?> PARAM_ERROR = new ApiResult<>(ApiResultCode.PARAM_ERROR, "参数错误");

    /**
     * 该方法不会被序列化
     */
    @Transient
    public boolean isSuccess() {
        return ApiResultCode.SUCCESS == this.code;
    }

    /**
     * 该方法不会被序列化
     */
    @Transient
    public boolean isFail() {
        return !isSuccess();
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
